<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { computed, ref } from 'vue';

import { AuthenticationCodeLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { message } from 'ant-design-vue';

import { getCaptchaApi } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'CodeLogin' });
const authStore = useAuthStore();
const loading = ref(false);
const registerForm = ref();
const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.mobile'),
      },
      fieldName: 'phoneNumber',
      label: $t('authentication.mobile'),
      rules: z
        .string()
        .min(1, { message: $t('authentication.mobileTip') })
        .refine((v) => /^\d{11}$/.test(v), {
          message: $t('authentication.mobileErrortip'),
        }),
    },
    {
      component: 'VbenPinInput',
      componentProps: {
        createText: (countdown: number) => {
          const text =
            countdown > 0
              ? $t('authentication.sendText', [countdown])
              : $t('authentication.sendCode');
          return text;
        },
        placeholder: $t('authentication.code'),
        handleSendCode: async () => {
          const data = await registerForm?.value?.getValues();
          const mySchema = z
            .string()
            .min(1, { message: $t('authentication.mobileTip') })
            .refine((v) => /^\d{11}$/.test(v), {
              message: $t('authentication.mobileErrortip'),
            });
          try {
            mySchema.parse(data.phoneNumber);
            // 提交表单格式
            const getCodeFrom: any = await getCaptchaApi({
              phoneNumber: data.phoneNumber,
              sendType: 2,
            });
            if (getCodeFrom) {
              message.success('验证码已发送');
              return true;
            }
            throw new Error('完善信息', getCodeFrom);
          } catch (error: any) {
            // console.log('error', error);
            // [].includes;
            !error.includes('完善信息') && message.error('请输入正确手机号');
            throw new Error('完善信息', error);
          }
        },
      },
      fieldName: 'code',
      label: $t('authentication.code'),
      rules: z.string().min(1, { message: $t('authentication.codeTip') }),
    },
  ];
});
/**
 * 异步处理登录操作
 * Asynchronously handle the login process
 * @param values 登录表单数据
 */
async function handleLogin(values: Recordable<any>) {
  authStore.authLoginForPhone({
    phoneNumber: values.phoneNumber,
    phoneCode: values.code,
  });
}
</script>

<template>
  <AuthenticationCodeLogin
    ref="registerForm"
    :form-schema="formSchema"
    :loading="loading"
    @submit="handleLogin"
  />
</template>
